// 注意：crypto-js，js-base64 需要通过 npm install 进行安装
import crypto from 'crypto-js';
import {
	Base64
} from 'js-base64';
import {
	axios
} from "@/request/axios.js";

/**
 * 1.  获取阿里云签名信息
 */
function getAliOssInfo() {
	return axios({
		url: '/alioss/getOssStsToken',
		method: 'get',
		headers: {
			token: uni.getStorageSync("token")
		}
	}) //接口由后台提供
}

// 计算签名。
function computeSignature(accessKeySecret, canonicalString) {
	return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

const date = new Date();
date.setHours(date.getHours() + 12);
// console.log('时间', date.toISOString())
const policyText = {
	expiration: date.toISOString(), // 设置policy过期时间。
	conditions: [
		// 限制上传大小。
		["content-length-range", 0, 1024 * 1024 * 1024],
	],
};


export const getFormDataParams = async () => {
	console.log('开始签名')
	const {
		data: res
	} = await getAliOssInfo()
	console.log(res)
	if (res === null || res.accessKeyId === null) {
		console.error("签名失败！");
		uni.showToast({
			title: '系统异常，请稍后再试...',
			icon: 'none'
		})
	} else {
		let credentials = res
		const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
		console.log("policy: ", policy);
		const signature = computeSignature(credentials.accessKeySecret, policy)
		console.log("signature: ", signature);
		const formData = {
			OSSAccessKeyId: credentials.accessKeyId,
			signature,
			policy,
			'x-oss-security-token': credentials.securityToken
		}
		console.log('签名成功：', formData)
		return formData
	}


}